<?php
declare (strict_types = 1);

namespace app\auth\service;

use app\auth\model\RightModel;

class RightService  extends BaseService
{
    public function __construct(RightModel $rightModel)
    {
        $this->rightModel = $rightModel;
    }

    public function model(){
        return $this->rightModel;
    }

    public function rightTree(){
        $where = [
            'status'=>RightModel::STATUS_NORMAL,
            'pid'=>0,
        ];
        $right_tree = $this->rightModel::with([RightModel::WITH_CHILDS])->where($where)->field(['name', 'url', 'id', 'type', 'value'])->select();
        return $right_tree ? $right_tree->toArray() : [];
    }

    /**
     * 权限筛选
     * @param array $rightTree
     * @param array $rights 指定权限[1,2,3,4]
     */
    public function rightTreeFilter(array $right_tree, array $rights = [], int $type = 0){
        $right_tree_new = [];
        foreach ($right_tree as $parent){
            $parent_new = $parent;
            foreach ($parent['childs'] as $key=>$child){
                //如果没有这个权限或权限类型不对则排除
                if (!in_array($child['id'], $rights) || ($type >0 && $child['type'] != $type))
                    unset($parent_new['childs'][$key]);

            }
            $parent_new['childs'] = array_values($parent_new['childs']);
            //如果子权限一个都没有了就排除掉
            if (count($parent_new['childs']))
                $right_tree_new[] = $parent_new;

        }
        return $right_tree_new;
    }

    public function list(array $where = [] , array $limit = [], array $sort= [],array $whereIn = []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        $model = $this->rightModel;
        $model = $model::with([RightModel::WITH_PARENT]);
        $model = $model->where($where);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        $model = $model->limit($limit['page'],$limit['pagesize']);
        $model = $model->order($sort[0],$sort[1]);
        return $model->select();
    }

    public function count(array $where = [],array $whereIn = []){
        $model = $this->rightModel;
        $model = $model->where($where);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        return $model->count();
    }

    public function select(array $where = [],array $fields = ['*']){
        return $this->rightModel->field($fields)->where($where)->select();
    }

    public function insertGetId(array $data = []){
        return $this->rightModel->insertGetId($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->rightModel->where($where)->update($data);
    }

    public function delete(array $whereIn = []){
        return $this->rightModel->whereIn($whereIn[0],$whereIn[1])->delete();
    }
}
